<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------
namespace app\Manage\controller;

use app\common\controller\Manage;
use app\common\model\Device as DeviceModel;
use app\common\model\Brand as BrandModel;
use app\common\model\DeviceCat as DeviceCatModel;
use app\common\model\DeviceType as DeviceTypeModel;
use app\common\model\FeeTemplate as FeeTemplateModel;
use app\common\model\DeviceTemplateRel as DeviceTemplateRelModel;
use app\common\model\DeviceTemplateRel as DeviceTemplateRel;

use think\facade\Request;
use think\facade\Log;

class Device extends Manage
{

    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if(Request::isAjax())
        {
            $deviceModel = new DeviceModel();
            return  $deviceModel->tableData(input('param.'));
        }

        // 获取品牌列表
        $deviceCatModel = new DeviceCatModel();
        $cat_nameList = $deviceCatModel->select();

        $brandModel = new BrandModel();
        $brandModelList = $brandModel->select();
 
        // 使用场景列表
        $deviceTypeModel = new DeviceTypeModel();
        $type_nameList = $deviceTypeModel->select();

        $this->assign('catList', $cat_nameList);
        $this->assign('brandList', $brandModelList);
        $this->assign('typeList', $type_nameList);

        return $this->fetch();
    }

    /**
     *  规则添加信息
     * User:tony
     * @return array|mixed
     */
    public function add()
    { 
        if(!input('?param.cat_id')){
            return error_code(10000);
        }
        if(!input('?param.brand_id')){
            return error_code(10000);
        } 
        if(!input('?param.type_id')){
            return error_code(10000);
        }
 
        $deviceModel = new DeviceModel();
        if(Request::isPost())
        { 
            // 判断是否有相同编号的设备
            $input     = Request::param();
            $data['cat_id'] = $input['cat_id'];
            $data['brand_id'] = $input['brand_id'];
            $data['type_id'] = $input['type_id'];
            $data['sub_id'] = $input['sub_id'];
            $deviceInfo = $deviceModel->tableData($data);
  
            if( $deviceInfo['count'] > 0) { 
                return [
                    'status' => false,
                    'data' => '',
                    'msg' => '已存在相同设备出厂编号！'
                ];
            }
 
            // 判断是否有互斥的计费规则
            if(isset($input['template_id'])){
                $data1 = [];
                foreach($input['template_id'] as $k => $v){
                    // 获取模板对应的计费参数 
                    $feeTemplateModel = new FeeTemplateModel();
                    $templateInfo = $feeTemplateModel->field('fee_name')->where(['id'=>$k])->find();
                    if (isset($templateInfo['fee_name']) && !empty($templateInfo['fee_name'])) {
                        if(isset($data1[$templateInfo['fee_name']])) {
                            return [
                                'status' => false,
                                'data' => '',
                                'msg' => '存在相同时间不同费用的计费规则'
                            ];
                        }
                        $data1[$templateInfo['fee_name']] = $templateInfo['fee_name'];
                    }
                } 
            }
            
            return $deviceModel->addData($input);
        }

        // 获取品牌列表
        $deviceCatModel = new DeviceCatModel();
        $cat_nameList = $deviceCatModel->select();

        $brandModel = new BrandModel();
        $brandModelList = $brandModel->select();
 
        // 使用场景列表
        $deviceTypeModel = new DeviceTypeModel();
        $type_nameList = $deviceTypeModel->select();

        $feeTemplateModel = new FeeTemplateModel();
        $templateList = $feeTemplateModel->order('sort desc')->select();
 
        $input     = Request::param();
        $cat_name = $deviceCatModel->getNameById($input['cat_id']);
        $type_name = $deviceTypeModel->getNameById($input['type_id']);
        $brand_name = $brandModel->getNameById($input['brand_id']);
        
        $info['cat_name'] = $cat_name;
        $info['type_name'] = $type_name;
        $info['brand_name'] = $brand_name;
        
        // 数据处理
        foreach ( $templateList as $key => $val ) {
            $templateList[$key]['templateInfo'] = '【'.$templateList[$key]['name'].'】 时长：【'.$templateList[$key]['fee_name'].'】 价格：【'.$templateList[$key]['money'].'】 ';
        }

        return $this->fetch('add',[
            'info'=>$info,
            'cat_id' => $cat_nameList,
            'type_id' => $type_nameList,
            'templateList' => $templateList,
            'brand_id' => $brandModelList]);
    }

    /**
     *
     *  规则信息编辑
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $deviceModel = new DeviceModel();
        if(Request::isPost())
        {
            // 判断是否有相同编号的设备
            $input     = Request::param();
            $data['cat_id'] = $input['cat_id'];
            $data['brand_id'] = $input['brand_id'];
            $data['type_id'] = $input['type_id'];
            $data['sub_id'] = $input['sub_id'];
            $deviceInfo = $deviceModel->tableData($data);
  
            if( $deviceInfo['count'] > 0 && $deviceInfo['data'][0]['id'] != $input['id']) {
                return [
                    'status' => false,
                    'data' => '',
                    'msg' => '已存在相同设备出厂编号！'
                ];
            }
            
            if( $deviceInfo['count'] == 0 && $deviceInfo['data'][0]['id'] != $input['id']) {
                $input['qrcode'] = '';
            }

            // 判断是否有互斥的计费规则
            if(isset($input['template_id'])){
                $data1 = [];
                foreach($input['template_id'] as $k => $v){
                    // 获取模板对应的计费参数 
                    $feeTemplateModel = new FeeTemplateModel();
                    $templateInfo = $feeTemplateModel->field('fee_name')->where(['id'=>$k])->find(); 
                    if (isset($templateInfo['fee_name']) && !empty($templateInfo['fee_name'])) {
                        if(isset($data1[$templateInfo['fee_name']])) {
                            return [
                                'status' => false,
                                'data' => '',
                                'msg' => '存在相同时间不同费用的计费规则'
                            ];
                        }
                        $data1[$templateInfo['fee_name']] = $templateInfo['fee_name'];
                    }
                } 
            }
             
            return $deviceModel->saveData($input);
        }
         
        $info = $deviceModel->where('id',input('param.id/d'))->find();
        if (!$info)
        {
            return error_code(10002);
        }

        // 获取品牌列表
        $deviceCatModel = new DeviceCatModel();
        $cat_nameList = $deviceCatModel->select();

        // 使用场景列表
        $deviceTypeModel = new DeviceTypeModel();
        $type_nameList = $deviceTypeModel->select();

        $brandModel = new BrandModel();
        $brandModelList = $brandModel->select();

        // 获取设备参数
        $deviceCatModel = new DeviceCatModel();
        $brandModel = new BrandModel();
        $deviceTypeModel = new DeviceTypeModel();

        $cat_name = $deviceCatModel->getNameById($info['cat_id']);
        $type_name = $deviceTypeModel->getNameById($info['type_id']);
        $brand_name = $brandModel->getNameById($info['brand_id']);
 
        $info['cat_name'] = $cat_name;
        $info['type_name'] = $type_name;
        $info['brand_name'] = $brand_name;
   
        $feeTemplateModel = new FeeTemplateModel();
        $templateList = $feeTemplateModel->order('sort desc')->select();
        //设置计费规则关联
        $deviceTemplateRel = new DeviceTemplateRelModel();  
        $curTemplateList = $deviceTemplateRel->where(['device_id'=>input('param.id/d')])->select();
        
        // 数据处理
        foreach ( $templateList as $k => $v) {
            $templateList[$k]['templateInfo'] = '【'.$templateList[$k]['name'].'】 时长：【'.$templateList[$k]['fee_name'].'】 价格：【'.$templateList[$k]['money'].'】 ';
        
            $checked = false;
            foreach($curTemplateList as $i => $j){
                if($j['template_id'] == $v['id']){
                    $checked = true;
                    break;
                }
            }
            $templateList[$k]['checked'] = $checked;
        }

        return $this->fetch('edit',[
            'info'=>$info,
            'cat_id' => $cat_nameList,
            'type_id' => $type_nameList,
            'templateList' => $templateList,
            'brand_id' => $brandModelList]);
    }
 
    /**
     *
     * 规则信息删除
     * User:tony
     * @return array
     */
    public function del()
    {
        $deviceModel = new DeviceModel();
        $result = ['status'=>false,'msg'=>'删除失败','data'=>''];
        if ($deviceModel::destroy(input('param.id/d'))) {
            //清空所有的计费规则
            $deviceTemplateRel = new DeviceTemplateRel();
            $deviceTemplateRel->where(['device_id'=>input('param.id/d')])->delete();
            
            $result['status'] = true;
            $result['msg'] = '删除成功';
        }

        return $result;
    }
 
    /***
     * 生成二维码
     */
    public function generate()
    {
        $id     = input('id/d', 0);
        $result = [
            'status' => false,
            'msg'    => '参数错误',
            'data'   => ''
        ];
        if (!$id) {
            echo $result['msg'];
            return;
        }
        $this->assign('id', $id);

        $deviceModel = new DeviceModel();
        $url = $deviceModel->GetWxCode($id);

        $this->view->engine->layout(false);
        return $this->fetch('qrcode',[
            'url' => $url]);
    }
 
    public function changeStatus()
    {
        $deviceModel = new DeviceModel();
        return $deviceModel->changeStatus(input('param.id/d'),input('param.status'));
    }
    
    /**
     * 导入设备
     * @return array|mixed
     */
    public function importDevice()
    {
        if (Request::isPost()) {
            // $input     = Request::param();
            // $userModel = new UserModel();
            // $result    = $userModel->manageAdd($input);
            // return $result;
        }
        return $this->fetch('importDevice');
    }

    /**
     * 批量启用设备
     * @return array|mixed
     */
    public function batchEnable()
    {
        $input     = Request::param();
        $where[] = ['id', 'in', $input['data']];

        $deviceModel = new DeviceModel();
        $flag = $deviceModel->where($where)->setField('status', $deviceModel::DEVICE_STATUS_YES);

        if (false === $flag) {
            return [
                'status' => false,
                'data' => '',
                'msg' => '更新失败！'
            ];
        } else {
            return [
                'status' => true,
                'data' => '',
                'msg' => '更新成功！'
            ];
        }
    }
     
    /**
     * 批量禁用设备
     * @return array|mixed
     */
    public function batchDisable()
    {
        $input     = Request::param();
        $where[] = ['id', 'in', $input['data']];

        $deviceModel = new DeviceModel();
        $flag = $deviceModel->where($where)->setField('status', $deviceModel::DEVICE_STATUS_NO);

        if (false === $flag) {
            return [
                'status' => false,
                'data' => '',
                'msg' => '更新失败！'
            ];
        } else {
            return [
                'status' => true,
                'data' => '',
                'msg' => '更新成功！'
            ];
        }
    }

    /**
     * 批量设置计费规则
     * @return array|mixed
     */
    public function batchFeeTemplate()
    {
        $this->view->engine->layout(false);
        $feeTemplateModel = new FeeTemplateModel();
        $templateList = $feeTemplateModel->order('sort desc')->select();
        //设置计费规则关联
        $deviceTemplateRel = new DeviceTemplateRelModel();  
        $curTemplateList = $deviceTemplateRel->where(['device_id'=>input('param.id/d')])->select();
        
        // 数据处理
        foreach ( $templateList as $k => $v) {
            $templateList[$k]['templateInfo'] = '【'.$templateList[$k]['name'].'】 时长：【'.$templateList[$k]['fee_name'].'】 价格：【'.$templateList[$k]['money'].'】 ';
        
            $checked = false;
            foreach($curTemplateList as $i => $j){
                if($j['template_id'] == $v['id']){
                    $checked = true;
                    break;
                }
            }
            $templateList[$k]['checked'] = $checked;
        }

        $input = Request::param();
     
        return $this->fetch('batchFeeTemplate',[ 
            'templateList' => $templateList,
            'deviceIds' => $input['deviceIds']]);
    }
    
    /**
     * 批量设置计费规则
     * @return array|mixed
     */
    public function batchFeeTemplateSave()
    {
        $deviceModel = new DeviceModel();
        return $deviceModel->batchFeeTemplateSave(input('param.'));
    }
}
